package com.sumainfor.pc.market.service;

import com.alibaba.fastjson.JSONArray;
import com.sumainfor.common.Constants;
import com.sumainfor.common.util.ContextUtils;
import com.sumainfor.common.util.JsonResult;
import com.sumainfor.common.util.ObjectUtil;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ConvertDateTime;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.pc.market.dao.*;
import org.apache.commons.collections.MapUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 *活动
 */
@Service
public class RdActivityService implements Serializable {

    private ReentrantLock lock = new ReentrantLock(false);

    Logger log = LoggerFactory.getLogger(RdActivityService.class);// 日志

    @Autowired
    private RdActivityMapper rdActivityMapper;

    public Map<String,Object> getOptimalActivity(Map<String,Object> params){
        System.out.println("params:"+params);
        //根据房源编号查询出房源的参与的活动编号
        BigDecimal leaseTerm=new BigDecimal(params.get("LeaseTerm").toString());//租几个月
        BigDecimal payType=new BigDecimal(params.get("PayType").toString()).add(new BigDecimal("1"));//租金支付方式
        System.out.println("payType:"+payType);
        params.put("PayType",payType);
        BigDecimal paMonthPrice=new BigDecimal(params.get("PaMonthPrice").toString());//合同月租金
//        BigDecimal grossRent=paMonthPrice.multiply(leaseTerm);//合同总金额
        List<Map<String,Object>> list=rdActivityMapper.getActivityList(params);
        Map<String,Object> resultMap=new HashMap<String,Object>();
        List<String> arrayList=new ArrayList<String>();
        System.out.println("list:"+list);
        if(list.size()>0){
            BigDecimal [] activityArray=new BigDecimal[list.size()];
            for (int i=0;i<list.size();i++){
                BigDecimal price=paMonthPrice;//房屋合租租金
                Map<String,Object> map=list.get(i);
                params.putAll(map);
                System.out.println("map:"+map);
                //活动规则一 签约满几个月享受的优惠
                Map<String,Object> map1=rdActivityMapper.getActivityFull(params);
                String sumRule="";
                String ruleContent1="";
                if(map1!=null){
                    BigDecimal fulDuration=new BigDecimal(map1.get("FulDuration").toString());//签满几个月
                    if (map1.get("IfType").toString().equals("1")){ //1 减金额 0打几折
                        if(leaseTerm.compareTo(fulDuration) > -1){//如果满足减金额的规则 大于等于
                            BigDecimal fulMoney= new BigDecimal(map1.get("FulMoney").toString());//减金额
                            price=price.subtract(fulMoney);
                            ruleContent1="签约时长大于"+fulDuration+"个月可享受月租金减"+fulMoney+"元的优惠";
                            sumRule=sumRule+ruleContent1+",";
                        }
                    }else{
                        if(leaseTerm.compareTo(fulDuration)> -1){//如果满足打几折的规则
                            BigDecimal FulOff=new BigDecimal(map1.get("FulOff").toString());//打几折
                            price=price.multiply(FulOff.multiply(new BigDecimal(0.1)).setScale(2,BigDecimal.ROUND_HALF_UP));
                            System.out.println("规则一FulOff："+FulOff);
                            System.out.println("规则一price："+price);
                            System.out.println("FulOff.divide(new BigDecimal(10),2)："+FulOff.multiply(new BigDecimal(0.1).setScale(2,BigDecimal.ROUND_HALF_UP)));
                            ruleContent1="签约时长大于"+fulDuration+"个月可享受月租金打"+FulOff+"折的优惠";
                            sumRule=sumRule+ruleContent1+",";
                        }
                    }
                }
                System.out.println("规则一："+price);
                //活动规则二 根据支付方式选择优惠
                Map<String,Object> map2=rdActivityMapper.getActivityPay(params);
                String ruleContent2="";
                if(map2!=null){
                    if(payType.compareTo(new BigDecimal(1)) == 0){
                        if (map2.get("IfType").toString().equals("1")){// 1月付  2季付  3半年付  4年付
                            BigDecimal fulMoney=new BigDecimal(map2.get("FulMoney").toString());//减金额
                            price=price.subtract(fulMoney);
                            ruleContent2="月付可享受月租金减"+fulMoney+"元的优惠";
                            sumRule=sumRule+ruleContent2+",";
                        }else{
                            BigDecimal FulOff=new BigDecimal(map2.get("FulOff").toString());//打几折
                            //price=price*(FulOff/10);
                            price=price.multiply(FulOff.multiply(new BigDecimal(0.1)).setScale(2,BigDecimal.ROUND_HALF_UP));
                            ruleContent2="月付可享受月租金打"+FulOff+"折的优惠";
                            sumRule=sumRule+ruleContent2+",";
                        }
                    }else if(payType.compareTo(new BigDecimal(2)) == 0){
                        if (map2.get("IfType").toString().equals("1")){// 1月付  2季付  3半年付  4年付
                            BigDecimal fulMoney=new BigDecimal(map2.get("FulMoney").toString());//减金额
                            price=price.subtract(fulMoney);
                            ruleContent2="季付可享受月租金减"+fulMoney+"元的优惠";
                            sumRule=sumRule+ruleContent2+",";
                        }else{
                            BigDecimal FulOff=new BigDecimal(map2.get("FulOff").toString());//打几折
                            price=price.multiply(FulOff.multiply(new BigDecimal(0.1)).setScale(2,BigDecimal.ROUND_HALF_UP));
                            ruleContent2="季付可享受月租金打"+FulOff+"折的优惠";
                            sumRule=sumRule+ruleContent2+",";
                        }
                    }else if(payType.compareTo(new BigDecimal(3)) == 0){
                        System.out.println("进入到月付");
                        if (map2.get("IfType").toString().equals("1")){// 1月付  2季付  3半年付  4年付
                            BigDecimal fulMoney=new BigDecimal(map2.get("FulMoney").toString());//减金额
                            price=price.subtract(fulMoney);
                            ruleContent2="半年付可享受月租金减"+fulMoney+"元的优惠";
                            sumRule=sumRule+ruleContent2+",";
                        }else{
                            BigDecimal FulOff=new BigDecimal(map2.get("FulOff").toString());//打几折
                            price=price.multiply(FulOff.multiply(new BigDecimal(0.1)).setScale(2,BigDecimal.ROUND_HALF_UP));
                            ruleContent2="半年付可享受月租金打"+FulOff+"折的优惠";
                            sumRule=sumRule+ruleContent2+",";
                        }
                    }else if(payType.compareTo(new BigDecimal(4)) == 0){
                        System.out.println("进入到年付");
                        if (map2.get("IfType").toString().equals("1")){// 1月付  2季付  3半年付  4年付
                            BigDecimal fulMoney=new BigDecimal(map2.get("FulMoney").toString());//减金额
                            price=price.subtract(fulMoney);
                            ruleContent2="年付可享受月租金减"+fulMoney+"元的优惠";
                            sumRule=sumRule+ruleContent2+",";
                        }else{
                            System.out.println("map2.get(\"FulOff\").toString():"+map2.get("FulOff").toString());
                            BigDecimal FulOff=new BigDecimal(map2.get("FulOff").toString());//打几折
                            price=price.multiply(FulOff.multiply(new BigDecimal(0.1)).setScale(2,BigDecimal.ROUND_HALF_UP));
                            ruleContent2="年付可享受月租金打"+FulOff+"折的优惠";
                            sumRule=sumRule+ruleContent2+",";
                        }
                    }
                }
                System.out.println("规则二："+price);
                //活动规则三 满几个月送几个月的优惠
                Map<String,Object> map3=rdActivityMapper.getActivitySend(params);
                String ruleContent3="";
                BigDecimal senSend;
                if(map3!=null){
                    BigDecimal senDuration=new BigDecimal(map3.get("SenDuration").toString());//获取签约的时长
                    senSend=new BigDecimal(map3.get("SenSend").toString());//获取满送的时长
                    //如果签约时长大于满送时长就享受优惠
                    if (senDuration.compareTo(senSend)> -1){
                        //送几个月
                        map.put("SenSend",senSend);
                        ruleContent3="入住满"+senDuration+"个月送"+senSend+"个月的优惠";
                        sumRule=sumRule+ruleContent3+",";
                    }else{
                        map.put("SenSend","0");
                        senSend=new BigDecimal("0");
                    }
                }else{
                    //送几个月
                    map.put("SenSend","0");
                    senSend=new BigDecimal("0");
                }
                System.out.println("规则三："+price);
                //活动规则四 首月签约优惠
                Map<String,Object> map4=rdActivityMapper.getActivityFirst(params);
                String ruleContent4="";
                if(map4!=null){//享受首月优惠
                    //签约时长加满送时长减首月
                    BigDecimal realTerm=leaseTerm.subtract(new BigDecimal("1"));
                    BigDecimal fulDuration=new BigDecimal(map4.get("FulDuration").toString());//获取签约的时长
                    BigDecimal fulMoney=new BigDecimal("0");//优惠的金额
                    if (leaseTerm.compareTo(fulDuration)> -1){
                        if (map4.get("IfType").toString().equals("1")){//1 减金额 0打几折
                            fulMoney=new BigDecimal(map4.get("FulMoney").toString());//减金额
                            ruleContent4="签约时长大于"+fulDuration+"个月可享受首月租金减"+fulMoney+"元的优惠";
                            sumRule=sumRule+ruleContent4+",";
                            //计算首月金额
                            map.put("Firstmonth",price.subtract(fulMoney));
                        }else{
                            BigDecimal FulOff=new BigDecimal(map4.get("FulOff").toString());//打几折
                            fulMoney=price.subtract(price.multiply(FulOff.multiply(new BigDecimal(0.1)).setScale(2,BigDecimal.ROUND_HALF_UP)));
                            ruleContent4="签约时长大于"+fulDuration+"个月可享受首月租金打"+FulOff+"折的优惠";
                            sumRule=sumRule+ruleContent4+",";
                            //计算首月金额
                            map.put("Firstmonth",price.subtract(fulMoney));
                        }
                    }
                    //平均金额(前端看到的活动后金额)
                    map.put("priceQian",(price.multiply(leaseTerm).subtract(fulMoney)).divide(leaseTerm.add(senSend),2));
                    //平均金额(每个月账单的金额)
                    map.put("priceHou",price);
                }else{//不享受优惠
                    //计算首月金额
                    map.put("Firstmonth",price);
                    //平均金额(前端看到的活动后金额)
                    map.put("priceQian",price);
                    //平均金额(每个月账单的金额)
                    map.put("priceHou",price);
                }
                System.out.println("规则四："+price);
                //活动规则五是否可以使用现金优惠券
                if(map.get("IfCoupon").toString().equals("0")){//是否可使用优惠券 0是 1否
                    String ruleContent5="可以使用现金优惠卷";
                    sumRule=sumRule+ruleContent5+",";
                }
                //去除多余的逗号
                if(!sumRule.equals("")) {
                    sumRule = sumRule.substring(0, sumRule.length() - 1);
                }
                //把活动规则存入到数组中
                map.put("ruleContent",sumRule);
                //把优惠后的价格作为key该活动编号作为value存入到map中
                map.put(map.get("priceQian").toString(),map.get("ActId"));
                activityArray[i]=new BigDecimal(map.get("priceQian").toString());
            }
            System.out.println("数组："+activityArray.length);
            //选择排序升序排列该房源所参与活动的 优惠后的价格
            for(int i=0;i<activityArray.length;i++) {
                int tem = i;
                for(int j=i;j<activityArray.length;j++) {
                    if(activityArray[j].compareTo(activityArray[tem])==1) {
                        tem = j;
                    }
                }
                BigDecimal temp1 = new BigDecimal(activityArray[i].toString());
                activityArray[i] = activityArray[tem];
                activityArray[tem] = temp1;
            }
            System.out.println("list:"+list);
            paMonthPrice=new BigDecimal(String.valueOf(activityArray[activityArray.length-1]));
            System.out.println("数组1:"+activityArray[0]);
            System.out.println("数组最后:"+activityArray[activityArray.length-1]);
            for (int z=0;z<activityArray.length;z++){
                System.out.println("数组"+z+"="+activityArray[z]);
            }
            resultMap.put("PaMonthPrice",paMonthPrice);
            //最优惠的活动价格作为key去匹配对应的活动编号
            for(Map<String,Object> sjMap:list){
                if (sjMap.containsKey(String.valueOf(paMonthPrice))){
                    System.out.println("找到activid:"+sjMap.get("ActId"));
                    resultMap.put("ActId",sjMap.get("ActId"));
                    resultMap.put("ruleContent",sjMap.get("ruleContent"));
                    resultMap.put("ActName",sjMap.get("ActName"));

                    Double zhengFirst = MapUtils.getDouble(sjMap,"Firstmonth");
                    Double zhengQian = MapUtils.getDouble(sjMap,"priceQian");
                    Double zhengHou = MapUtils.getDouble(sjMap,"priceHou");
                    resultMap.put("Firstmonth",Math.round(zhengFirst));
                    resultMap.put("priceQian",Math.round(zhengQian));
                    resultMap.put("priceHou",Math.round(zhengHou));
//                    resultMap.put("Firstmonth",sjMap.get("Firstmonth"));
//                    resultMap.put("priceQian",sjMap.get("priceQian"));
//                    resultMap.put("priceHou",sjMap.get("priceHou"));
                    resultMap.put("SenSend",sjMap.get("SenSend"));
                }
            }
        }else{

          //  resultMap.put("ActId","");
           // resultMap.put("ruleContent","");
           // resultMap.put("ActName","");
            resultMap.put("Firstmonth",params.get("PaMonthPrice"));
            resultMap.put("priceQian",params.get("PaMonthPrice"));
            resultMap.put("priceHou",params.get("PaMonthPrice"));
            resultMap.put("SenSend",0);

        }


        return  resultMap;
    }




    /**
     * 签约时如果活动为满减类，计算合同结束周期
     * @author zhoucong
     * @data 2019/10/14
     * @Param
     * @return
     */
    public JsonResult getActIdSend(Map<String,Object> params){
        JsonResult result = new JsonResult();
        Map<String,Object> mapOne = new HashMap<>();
        Map<String,Object> getActIdSend = rdActivityMapper.getActIdSend(params);
        if (getActIdSend!=null){
            getActIdSend.put("There",1);
            Integer a = MapUtils.getInteger(getActIdSend,"SenSend");
            String time = MapUtils.getString(params,"EndTime");
            DateTime dateTimeOne = new DateTime(time);
            try {
                 String time1 = (ConvertDateTime.addDateTime(dateTimeOne,a,5)).toString("yyyy-MM-dd");
                mapOne.put("EndTimeOne",time1);
                mapOne.putAll(getActIdSend);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            mapOne.put("Three",0);
        }
        return result.put(mapOne);
    }

}
